<?php
/**
 * SocialEngine
 *
 * @category   Application_Core
 * @package    Socialengineaddon
 * @copyright  Copyright 2006-2010 Webligo Developments
 * @license    http://www.socialengine.net/license/
 * @version    $Id: ActivityController.php 2011-09-26 20:37:57Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Socialengineaddon_ActivityController extends Core_Controller_Action_Standard {
	
	public function postAction() {
		// Make sure user exists
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		// Get subject if necessary
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$subject = null;
		$subject_guid = $this->_getParam ( 'subject', null );
		if ($subject_guid) {
			$subject = Engine_Api::_ ()->getItemByGuid ( $subject_guid );
		}
		// Use viewer as subject if no subject
		if (null === $subject) {
			$subject = $viewer;
		}
		
		// Make form
		$form = $this->view->form = new Activity_Form_Post ();
		
		// Check auth
		if (! $subject->authorization ()->isAllowed ( $viewer, 'comment' )) {
			return $this->_helper->requireAuth ()->forward ();
		}
		
		// Check if post
		if (! $this->getRequest ()->isPost ()) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Not post' );
			return;
		}
		
		// Check if form is valid
		$postData = $this->getRequest ()->getPost ();
		$body = @$postData ['body'];
		$body = html_entity_decode ( $body, ENT_QUOTES, 'UTF-8' );
		$body = html_entity_decode ( $body, ENT_QUOTES, 'UTF-8' );
		//$body = htmlentities($body, ENT_QUOTES, 'UTF-8');
		$postData ['body'] = $body;
		
		if (! $form->isValid ( $postData )) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Invalid data' );
			return;
		}
		
		// Check one more thing
		if ($form->body->getValue () === '' && $form->getValue ( 'attachment_type' ) === '') {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Invalid data' );
			return;
		}
		
		// set up action variable
		$action = null;
		
		// Process
		$db = Engine_Api::_ ()->getDbtable ( 'actions', 'activity' )->getAdapter ();
		$db->beginTransaction ();
		
		try {
			// Try attachment getting stuff
			$attachment = null;
			$attachmentData = $this->getRequest ()->getParam ( 'attachment' );
			
			if (! empty ( $attachmentData ) && ! empty ( $attachmentData ['type'] )) {
				$type = $attachmentData ['type'];
				
				$config = null;
				foreach ( Zend_Registry::get ( 'Engine_Manifest' ) as $data ) {
					
					if (! empty ( $data ['composer'] [$type] )) {
						$config = $data ['composer'] [$type];
					}
				}
				if (! empty ( $config ['auth'] ) && ! Engine_Api::_ ()->authorization ()->isAllowed ( $config ['auth'] [0], null, $config ['auth'] [1] )) {
					$config = null;
				}
				
				if ($config) {
					$typeExplode = explode ( "-", $type );
					for($i = 1; $i < count ( $typeExplode ); $i ++)
						$typeExplode [$i] = ucfirst ( $typeExplode [$i] );
					$type = implode ( "", $typeExplode );
					$plugin = Engine_Api::_ ()->loadClass ( $config ['plugin'] );
					$method = 'onAttach' . ucfirst ( $type );
					$attachment = $plugin->$method ( $attachmentData );
				}
			}
			
			// Get body
			$body = $form->getValue ( 'body' );
			$body = preg_replace ( '/<br[^<>]*>/', "\n", $body );
			
			// Is double encoded because of design mode
			//$body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
			//$body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
			//$body = htmlentities($body, ENT_QUOTES, 'UTF-8');
			// Special case: status
			$activityTable = Engine_Api::_ ()->getDbtable ( 'actions', 'activity' );
			if (! $attachment && $viewer->isSelf ( $subject )) {
				if ($body != '') {
					$viewer->status = $body;
					$viewer->status_date = date ( 'Y-m-d H:i:s' );
					$viewer->save ();
					
					$viewer->status ()->setStatus ( $body );
				}
				
				$action = $activityTable->addActivity ( $viewer, $subject, 'status', $body );
			} else { // General post
				$type = 'post';
				if ($viewer->isSelf ( $subject )) {
					$type = 'post_self';
				}
				
				// Add notification for <del>owner</del> user
				$subjectOwner = $subject->getOwner ();
				
				if (! $viewer->isSelf ( $subject ) && $subject instanceof User_Model_User) {
					$notificationType = 'post_' . $subject->getType ();
					Engine_Api::_ ()->getDbtable ( 'notifications', 'activity' )->addNotification ( $subjectOwner, $viewer, $subject, $notificationType, array ('url1' => $subject->getHref () ) );
				}
				
				// Add activity
				if ($subject->getType () == "sitepage_page") {
					if (Engine_Api::_ ()->sitepage ()->isPageOwner ( $subject ) && Engine_Api::_ ()->sitepage ()->isFeedTypePageEnable ())
						$action = Engine_Api::_ ()->getDbtable ( 'actions', 'socialengineaddon' )->addActivity ( $subject, $viewer, 'sitepage_post_self', $body );
					elseif ($subject->all_post || Engine_Api::_ ()->sitepage ()->isPageOwner ( $subject ))
						$action = $activityTable->addActivity ( $viewer, $subject, 'sitepage_post', $body );
				} else {
					$action = $activityTable->addActivity ( $viewer, $subject, $type, $body );
				}
				// Try to attach if necessary
				if ($action && $attachment) {
					$activityTable->attachActivity ( $action, $attachment );
				}
			}
			
			// Publish to facebook, if checked & enabled
			if ($this->_getParam ( 'post_to_facebook', false ) && 'publish' == Engine_Api::_ ()->getApi ( 'settings', 'core' )->core_facebook_enable) {
				try {
					
					$facebookTable = Engine_Api::_ ()->getDbtable ( 'facebook', 'user' );
					$facebook = $facebookApi = $facebookTable->getApi ();
					$fb_uid = $facebookTable->find ( $viewer->getIdentity () )->current ();
					
					if ($fb_uid && $fb_uid->facebook_uid && $facebookApi && $facebookApi->getUser () && $facebookApi->getUser () == $fb_uid->facebook_uid) {
						$url = 'http://' . $_SERVER ['HTTP_HOST'] . $this->getFrontController ()->getBaseUrl ();
						$name = 'Activity Feed';
						$desc = '';
						$picUrl = $viewer->getPhotoUrl ( 'thumb.icon' );
						if ($attachment) {
							$url = $attachment->getHref ();
							$desc = $attachment->getDescription ();
							$name = $attachment->getTitle ();
							if (empty ( $name )) {
								$name = ucwords ( $attachment->getShortType () );
							}
							$tmpPicUrl = $attachment->getPhotoUrl ();
							if ($tmpPicUrl) {
								$picUrl = $tmpPicUrl;
							}
							// prevents OAuthException: (#100) FBCDN image is not allowed in stream
							if (preg_match ( '/fbcdn.net$/i', parse_url ( $picUrl, PHP_URL_HOST ) )) {
								$picUrl = $viewer->getPhotoUrl ( 'thumb.icon' );
							}
						}
						
						// Check stuff
						if (false === stripos ( $url, 'http://' )) {
							$url = 'http://' . $_SERVER ['HTTP_HOST'] . $url;
						}
						if (false === stripos ( $picUrl, 'http://' )) {
							$picUrl = 'http://' . $_SERVER ['HTTP_HOST'] . $picUrl;
						}
						
						// include the site name with the post:
						$name = Engine_Api::_ ()->getApi ( 'settings', 'core' )->core_general_site_title . ": $name";
						
						$fb_data = array ('message' => html_entity_decode ( $form->getValue ( 'body' ) ), 'link' => $url, 'name' => $name, 'description' => $desc );
						
						if ($picUrl) {
							$fb_data = array_merge ( $fb_data, array ('picture' => $picUrl ) );
						}
						
						$res = $facebookApi->api ( '/me/feed', 'POST', $fb_data );
					}
				} catch ( Exception $e ) {
					// Silence
				}
			} // end Facebook
			// Publish to twitter, if checked & enabled
			if ($this->_getParam ( 'post_to_twitter', false ) && 'publish' == Engine_Api::_ ()->getApi ( 'settings', 'core' )->core_twitter_enable) {
				try {
					$twitterTable = Engine_Api::_ ()->getDbtable ( 'twitter', 'user' );
					if ($twitterTable->isConnected ()) {
						// @todo truncation?
						// @todo attachment
						$twitter = $twitterTable->getApi ();
						$twitter->statuses->update ( html_entity_decode ( $form->getValue ( 'body' ) ) );
					}
				} catch ( Exception $e ) {
					// Silence
				}
			}
			
			$db->commit ();
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e; // This should be caught by error handler
		}
		
		// If we're here, we're done
		$this->view->status = true;
		$this->view->message = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Success!' );
		
		// Check if action was created
		$post_fail = "";
		if (! $action) {
			$post_fail = "?pf=1";
		}
		
		// Redirect if in normal context
		if (null === $this->_helper->contextSwitch->getCurrentContext ()) {
			$return_url = $form->getValue ( 'return_url', false );
			if ($return_url) {
				return $this->_helper->redirector->gotoUrl ( $return_url . $post_fail, array ('prependBase' => false ) );
			}
		}
	}

}